package logic

import (
	"gvb-server/Request"
	"gvb-server/global"
	"gvb-server/models"
	"gvb-server/utils"
)

var err error
var totalRows int64
var totalPages int64

func (a Advert) GetList(s Request.AdvertRequest) (utils.RList[models.Advert], error) {
	var ad []models.Advert
	var rb utils.RList[models.Advert] // 注意这里

	w := map[string]any{
		"status": 1,
	}

	// 获取总数
	global.DB.Model(models.Advert{}).Count(&totalRows)
	if err != nil {
		return rb, err
	}

	// 开始分页
	if totalRows%int64(s.Size) == 0 {
		totalPages = totalRows / int64(s.Size)
	} else {
		totalPages = (totalRows / int64(s.Size)) + 1
	}

	// 排序
	sort := "create_date asc"
	if s.Sort == "" {
		sort = "create_date desc"
	}

	// 直接用find关联表
	err = global.DB.Limit(s.Size).Offset((s.Page - 1) * s.Size).Order(sort).Where(w).Find(&ad).Error

	rb.List = ad
	rb.Page = s.Page
	rb.Size = s.Size
	rb.TotalPages = totalPages
	return rb, err
}

func (a Advert) DelAdvert(s Request.AdvertDelRequest) (pub utils.PubStatus) {
	models.DelByIds(s)
	pub.Status = utils.SUCCESS
	pub.Msg = "删除成功"
	return
}

// CreateAdvert 修改文件
func (a Advert) CreateAdvert(s Request.AdvertCreateRequest) (pub utils.PubStatus) {
	r := models.CreateData(s)
	pub.Status = utils.SUCCESS
	pub.Msg = "新增成功"
	if r.Status == utils.ERROR {
		pub.Status = r.Status
		pub.Msg = r.Msg
	}
	return
}

// UpdateAdvert 修改文件
func (a Advert) UpdateAdvert(s Request.AdvertEditRequest) (pub utils.PubStatus) {
	models.UpdateByIds(s)
	pub.Status = utils.SUCCESS
	pub.Msg = "修改成功"
	return
}
